<template>
  <div class="min-h-screen bg-gray-50 flex flex-col md:flex-row">
    <!-- 左侧导航栏 -->
    <!-- <Nav class="md:flex-shrink-0 w-full md:w-auto"></Nav> -->
    <Nav></Nav>

    <!-- 右侧主体内容 -->
    <div class="flex-1 h-screen flex flex-col">
   <!-- 顶部标题区域 -->
   <div class="p-4 md:p-8 pb-2 md:pb-4 flex-none bg-white shadow-sm">
        <div class="flex justify-between items-center">
          <div>
            <h1 class="text-lg md:text-xl font-semibold text-gray-800 mb-1">{{ testInfo.title }}</h1>
            <p class="text-xs md:text-sm text-gray-500">共 {{ questions.length }} 题</p>
          </div>
          <div class="flex items-center">
            <div class="mr-4 text-sm text-gray-600">
              <el-progress 
                type="circle" 
                :percentage="progressPercentage" 
                :width="60"
                :stroke-width="6"
                :show-text="false"
                class="mr-2"
              ></el-progress>
              <span class="ml-2">{{ answeredCount }}/{{ questions.length }}</span>
            </div>
            <div 
              class="text-sm"
              :class="[
                remainingTime <= 5 ? 'text-red-600 animate-pulse' : 'text-gray-600'
              ]">
              <el-statistic :value="remainingTime">
                <template #title>
                  <div class="text-xs" :class="remainingTime <= 5 ? 'text-red-500' : 'text-gray-500'">
                    {{ remainingTime <= 5 ? '即将结束' : '剩余时间' }}
                  </div>
                </template>
                <template #suffix>分钟</template>
              </el-statistic>
            </div>
          </div>
        </div>
      </div>

      <div class="flex-1 overflow-hidden flex flex-col md:flex-row">
        <!-- 左侧题目区域 -->
        <div class="flex-1 overflow-y-auto p-4 md:p-8">
          <div class="bg-white rounded-xl p-6 shadow-sm mb-6">
            <!-- 题目类型和序号 -->
            <div class="flex justify-between items-center mb-4">
              <div class="flex items-center">
                <span class="px-3 py-1 bg-blue-100 text-blue-800 text-xs rounded-full mr-2">
                  {{ getQuestionTypeName(currentQuestion.type) }}
                </span>
                <span class="text-gray-500 text-sm">第 {{ currentIndex + 1 }} 题</span>
              </div>
              <div class="flex items-center">
                <el-button 
                  v-if="currentIndex > 0" 
                  @click="goToQuestion(currentIndex - 1)" 
                  text 
                  class="text-gray-600">
                  <el-icon><ArrowLeft /></el-icon> 上一题
                </el-button>
                <el-button 
                  v-if="currentIndex < questions.length - 1" 
                  @click="goToQuestion(currentIndex + 1)" 
                  text 
                  class="text-gray-600">
                  下一题 <el-icon><ArrowRight /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 题目内容 -->
            <div class="mb-6">

              <!-- 单选题 -->
              <div v-if="currentQuestion.type === 'single'" class="space-y-3">
                <div class="text-base md:text-lg font-medium text-gray-800 mb-4" v-html="currentQuestion.content"></div>
                <div 
                  v-for="(text, key) in currentQuestion.options" 
                  :key="key"
                  @click="selectOption(key)"
                  :class="[
                    'p-3 border rounded-lg cursor-pointer flex items-start transition-all',
                    currentQuestion.answer === key
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300'
                  ]">
                  <div class="flex-shrink-0 mr-3">
                    <div 
                      :class="[
                        'w-6 h-6 flex items-center justify-center rounded-full border text-sm font-medium',
                        currentQuestion.answer === key
                          ? 'bg-blue-500 text-white border-blue-500'
                          : 'border-gray-300 text-gray-500'
                      ]">
                      {{ key }}
                    </div>
                  </div>
                  <div class="flex-1" v-html="text"></div>
                </div>
              </div>

              <!-- 多选题 -->
              <div v-if="currentQuestion.type === 'multiple'" class="space-y-3">
                <div class="text-base md:text-lg font-medium text-gray-800 mb-4" v-html="currentQuestion.content"></div>
                <div 
                  v-for="(option, index) in currentQuestion.options" 
                  :key="index"
                  @click="selectOption(option.value)"
                  :class="[
                    'p-3 border rounded-lg cursor-pointer flex items-start transition-all',
                    isOptionSelected(option.value) 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300'
                  ]">
                  <div class="flex-shrink-0 mr-3">
                    <div 
                      :class="[
                        'w-6 h-6 flex items-center justify-center rounded-lg border text-sm font-medium',
                        isOptionSelected(option.value)
                          ? 'bg-blue-500 text-white border-blue-500'
                          : 'border-gray-300 text-gray-500'
                      ]">
                      {{ String.fromCharCode(65 + index) }}
                    </div>
                  </div>
                  <div class="flex-1" v-html="option.text"></div>
                </div>
              </div>

              <!-- 判断题 -->
              <div v-else-if="currentQuestion.type === 'truefalse'" class="space-y-4">
                <div class="text-base md:text-lg font-medium text-gray-800" v-html="currentQuestion.content"></div>
                <div class="flex gap-4">
                  <div 
                    @click="selectOption(true)"
                    :class="[
                      'flex-1 p-4 border rounded-lg cursor-pointer flex items-center justify-center transition-all',
                      currentQuestion.answer === true
                        ? 'border-blue-500 bg-blue-50 text-blue-600'
                        : 'border-gray-200 hover:border-gray-300 text-gray-600'
                    ]">
                    <el-icon class="mr-2"><Check /></el-icon> 正确
                  </div>
                  <div 
                    @click="selectOption(false)"
                    :class="[
                      'flex-1 p-4 border rounded-lg cursor-pointer flex items-center justify-center transition-all',
                      currentQuestion.answer === false
                        ? 'border-blue-500 bg-blue-50 text-blue-600'
                        : 'border-gray-200 hover:border-gray-300 text-gray-600'
                    ]">
                    <el-icon class="mr-2"><Close /></el-icon> 错误
                  </div>
                </div>
              </div>

              <!-- 填空题 -->
              <div v-if="currentQuestion.type === 'fillblank'" class="space-y-4">
                <div class="text-base md:text-lg font-medium text-gray-800 mb-4" v-html="processBlankContent(currentQuestion.content)"></div>
                <div 
                  v-for="(_, index) in getBlankCount()" 
                  :key="index"
                  class="flex items-center mb-2">
                  <span class="mr-2 text-gray-600">第{{ index + 1 }}空：</span>
                  <el-input 
                    v-model="currentQuestion.answer[index]"
                    placeholder="请填写答案"
                    class="flex-1"
                    @input="updateAnswer"></el-input>
                </div>
              </div>

              <!-- 应答题 -->
              <div v-else-if="currentQuestion.type === 'essay'" class="space-y-4">
                <div class="text-base md:text-lg font-medium text-gray-800 mb-4" v-html="currentQuestion.content"></div>
                <el-input 
                  v-model="currentQuestion.answer" 
                  type="textarea" 
                  :rows="6"
                  placeholder="请输入你的答案..."
                  @input="updateAnswer"></el-input>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧题目导航 -->
        <div class="w-full md:w-64 p-4 bg-white border-t md:border-t-0 md:border-l border-gray-200 flex flex-col">
          <h3 class="text-sm font-medium text-gray-700 mb-4">题目导航</h3>
          
          <div class="flex flex-wrap gap-2 mb-4">
            <div 
              v-for="(q, index) in questions" 
              :key="index"
              @click="goToQuestion(index)"
              :class="[
                'w-8 h-8 flex items-center justify-center rounded-lg cursor-pointer text-sm transition-all',
                currentIndex === index 
                  ? 'bg-blue-500 text-white' 
                  : isQuestionAnswered(q) 
                    ? 'bg-green-100 text-green-800 border border-green-200' 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              ]">
              {{ index + 1 }}
            </div>
          </div>

          <div class="flex items-center text-xs text-gray-500 mb-6">
            <div class="flex items-center mr-4">
              <div class="w-3 h-3 bg-gray-100 rounded mr-1"></div>
              <span>未作答</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-green-100 rounded mr-1 border border-green-200"></div>
              <span>已作答</span>
            </div>
          </div>

          <el-button 
            type="primary" 
            class="w-full" 
            :disabled="answeredCount !== questions.length"
            @click="submitTest">
            {{ answeredCount === questions.length ? '提交试卷' : `还需完成 ${questions.length - answeredCount} 题` }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import Nav from '@/components/nav/index.vue'
import { getPaper,savePaperAnswer } from '@/api/common'
import { useRoute,useRouter } from 'vue-router'
import { id } from 'element-plus/es/locales.mjs'
import { convertQuestionType, getDefaultAnswer, processOptions } from '@/utils/questionHelper'


export default {
  components: { Nav, Check, Close, ArrowLeft, ArrowRight },
  setup() {
    // 测试信息
    const testInfo = ref({
      id: '',
      title: '期末考试',
      // totalScore: 100,
      duration: 120, // 考试时长（分钟）
    })
    const route = useRoute()
    const router = useRouter()
    // 题目列表
    const questions = ref([])
    const currentIndex = ref(0)
    const currentQuestion = computed(() => questions.value[currentIndex.value] || {})

    // 答题进度
    const answeredCount = computed(() => {
      return questions.value.filter(q => isQuestionAnswered(q)).length
    })
    const progressPercentage = computed(() => {
      return Math.round((answeredCount.value / questions.value.length) * 100)
    })

    // 倒计时
    const remainingTime = ref(testInfo.value.duration)
    let timer = null

    // 自动保存
    const autoSaveInterval = 30000 // 30秒
    let autoSaveTimer = null

    const paper = ref({})
    // 加载题目
    const loadQuestions = async () => {
      try {
        // 从 store 获取试卷 ID 并调用 API
          const res = await getPaper({
            id: route.query.paper_id
          })
          paper.value = res.paper

          questions.value = res.questions.map(item => ({
            id: item.questionId,
            type: convertQuestionType(item.baseType),
            content: item.stem,
            options: processOptions(item.options),
            answer: getDefaultAnswer(convertQuestionType(item.baseType))
          })) || []
          // 根据题目数量设置考试时长
          const questionCount = questions.value.length
          testInfo.value.id = res.paper.id
          testInfo.value.duration = Math.floor(questionCount / 10) * 30
          testInfo.value.title = `${res.paper.title} · ${res.paper.version_name} · ${res.paper.grade_name} · ${res.paper.term_type_name}`
          // `${state.paperData.type === 1 ? '能力测评' : '单元测试'} · ${state.paperData.version_name} · ${state.paperData.grade_name} · ${state.paperData.term_type_name}`
          return res
      } catch (error) {
        console.error('加载试题出错：', error)
        ElMessage.error('加载试题失败，请刷新页面重试')
      }
    }

    // 初始化数据
    onMounted(() => {
      // 加载题目数据
      loadQuestions()
      // 启动倒计时
      startTimer()
      // 启动自动保存
      startAutoSave()
      // 添加页面关闭提醒
      window.addEventListener('beforeunload', handleBeforeUnload)
    })

    onUnmounted(() => {
      clearInterval(timer)
      clearInterval(autoSaveTimer)
      window.removeEventListener('beforeunload', handleBeforeUnload)
    })


    const processBlankContent = (content) => {
      if (!content) return ''
      let processedContent = content
      // 替换填空标记为带下划线的空格
      processedContent = processedContent.replace(
        /\{#blank#\}\d+\{#\/blank#\}/g,
        '<u class="inline-block mx-2 min-w-[60px] border-b-2 border-gray-300"></u>'
      )
      return processedContent
    }

    // 获取当前题目的填空数量
    const getBlankCount = () => {
      if (!currentQuestion.value?.content) return []
      const matches = currentQuestion.value.content.match(/\{#blank#\}\d+\{#\/blank#\}/g) || []
      
      // 确保 answer 是数组
      if (!currentQuestion.value.answer || !Array.isArray(currentQuestion.value.answer)) {
        currentQuestion.value.answer = new Array(matches.length).fill('')
      }
      
      return matches
    }

    // 获取填空题答案
    const getBlankAnswer = (index) => {
      if (!currentQuestion.value.answer || !Array.isArray(currentQuestion.value.answer)) {
        return ''
      }
      return currentQuestion.value.answer[index] || ''
    }

    // 更新填空题答案
    const updateBlankAnswer = (index, value) => {
      if (!currentQuestion.value.answer || !Array.isArray(currentQuestion.value.answer)) {
        currentQuestion.value.answer = new Array(getBlankCount().length).fill('')
      }
      currentQuestion.value.answer[index] = value
      updateAnswer()
    }
    
    // 初始化填空题答案数组
    const initBlankAnswer = (index) => {
      if (!currentQuestion.value.answer) {
        // 如果答案为null，初始化为空数组
        currentQuestion.value.answer = new Array(getBlankCount().length).fill('')
      } else if (!Array.isArray(currentQuestion.value.answer)) {
        // 如果答案不是数组，转换为数组
        const blankCount = getBlankCount().length
        currentQuestion.value.answer = new Array(blankCount).fill('')
      }
      
      // 确保数组长度足够
      while (currentQuestion.value.answer.length < getBlankCount().length) {
        currentQuestion.value.answer.push('')
      }
      
      updateAnswer()
    }

    // 倒计时
    const startTimer = () => {
      timer = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--
          // 最后5分钟提醒
          if (remainingTime.value === 5) {
            ElMessage({
              message: '距离考试结束还有5分钟，请抓紧时间！',
              type: 'warning',
              duration: 0,
              showClose: true
            })
          }
        } else {
          clearInterval(timer)
          autoSubmit()
        }
      }, 60000) // 每分钟更新一次
    }

    // 自动保存
    const startAutoSave = () => {
      autoSaveTimer = setInterval(() => {
        saveAnswers()
      }, autoSaveInterval)
    }

    // 保存答案
    const saveAnswers = () => {
      const answers = questions.value.map(q => ({
        id: q.id,
        answer: q.answer
      }))
      // 这里添加保存到本地存储或发送到服务器的逻辑
      localStorage.setItem('answers'+ testInfo.value.id, JSON.stringify(answers))
    //   ElMessage.success('答案已自动保存')
    }

    // 自动提交
    const autoSubmit = () => {
      ElMessage.warning('考试时间已到，系统将自动提交试卷')
      submitTest()
    }

    // 判断题目是否已答
    const isQuestionAnswered = (question) => {
      if (!question.answer) return false
      
      switch (question.type) {
        case 'single':
        case 'truefalse':
          return question.answer !== null
        case 'multiple':
          return Array.isArray(question.answer) && question.answer.length > 0
        case 'fillblank':
          return Array.isArray(question.answer) && 
                 question.answer.every(ans => ans && ans.trim() !== '')
        case 'essay':
          return question.answer && question.answer.trim() !== ''
        default:
          return false
      }
    }

    // 获取题型名称
    const getQuestionTypeName = (type) => {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        truefalse: '判断题',
        fillblank: '填空题',
        essay: '应答题'
      }
      return typeMap[type] || '未知题型'
    }

     // 判断多选题选项是否被选中
     const isOptionSelected = (value) => {
      if (!currentQuestion.value.answer) return false
      return currentQuestion.value.answer.includes(value)
    }

    const splitContent = computed(() => {
      if (!currentQuestion.value?.content) return []
      return currentQuestion.value.content.split(/\{#blank#\}\d+\{#\/blank#\}/)
    })

    // 选择答案
    const selectOption = (value) => {
      if (currentQuestion.value.type === 'multiple') {
        if (!Array.isArray(currentQuestion.value.answer)) {
          currentQuestion.value.answer = []
        }
        const index = currentQuestion.value.answer.indexOf(value)
        if (index === -1) {
          currentQuestion.value.answer.push(value)
        } else {
          currentQuestion.value.answer.splice(index, 1)
        }
      } else {
        currentQuestion.value.answer = value
        // 单选题和判断题选择后自动跳转到下一题
        if ((currentQuestion.value.type === 'single' || currentQuestion.value.type === 'truefalse') 
            && currentIndex.value < questions.value.length - 1) {
          setTimeout(() => {
            goToQuestion(currentIndex.value + 1)
          }, 300) // 短暂延迟以便用户看到选择效果
        }
      }
      updateAnswer()
    }

    // 更新答案
    const updateAnswer = () => {
      // 这里可以添加实时保存的逻辑
    }

    // 跳转到指定题目
    const goToQuestion = (index) => {
      currentIndex.value = index
    }

    // 页面关闭提醒
    const handleBeforeUnload = (e) => {
      e.preventDefault()
      e.returnValue = ''
    }

    // 提交试卷
// 提交试卷
const submitTest = () => {
      ElMessageBox.confirm('确认提交试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning' 
      }).then(() => {
        // 计算考试用时（分钟），确保最低为1分钟
        const usedTime = Math.max(1, testInfo.value.duration - remainingTime.value);
        
        // 收集所有答案
        const answers = questions.value.map(q => ({
          questionId: q.id,
          answer: q.answer
        }));
        
        // 构建提交数据
        const submitData = {
          id: testInfo.value.id,
          minute: usedTime, // 使用时间（分钟）
          answer_json: answers, // 答案集合
          submitTime: new Date().toISOString() // 提交时间
        };
        
        console.log('提交试卷数据:', submitData);
        
        // TODO: 这里添加提交到服务器的API调用
        // 例如: submitPaperAnswers(submitData)
        savePaperAnswer(submitData).then(response => {
          // 处理服务器响应
          console.log('提交结果:', response); 
        })
        
        // 保存到本地存储（备份）
        localStorage.setItem(`paperSubmit_${testInfo.value.id}`, JSON.stringify(submitData));
        
        // 显示成功消息
        ElMessage.success('试卷提交成功！');
        
        // 清除定时器
        clearInterval(timer);
        clearInterval(autoSaveTimer);
        
        // 跳转到结果页面或其他操作
        router.push({
          path: '/result',
          query: { paper_id: testInfo.value.id }
        });
      }).catch(() => {
        // 用户取消提交
        ElMessage.info('已取消提交');
      });
    }

    return {
      testInfo,
      questions,
      currentIndex,
      currentQuestion,
      answeredCount,
      progressPercentage,
      remainingTime,
      getQuestionTypeName,
      isOptionSelected, 
      selectOption,
      isQuestionAnswered,
      goToQuestion,
      updateAnswer,
      submitTest,
      processBlankContent,
      getBlankCount,
      initBlankAnswer,
      getBlankAnswer,
      updateBlankAnswer,
      splitContent
    }
  }
}
</script>

<style scoped>
/* 题干中的图片样式 */
:deep(img) {
  display: inline-block;
  vertical-align: middle;
  margin: 0 4px;
}

/* 添加一些动画效果提升用户体验 */
.el-button {
  transition: all 0.3s ease;
}

/* 题目导航按钮悬停效果 */
[class*='bg-gray-100']:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 当前题目高亮效果 */
[class*='bg-blue-500'] {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .flex-row {
    flex-direction: column;
  }
  .w-64 {
    width: 100%;
  }
}

/* 倒计时动画 */
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

/* 优化题目导航样式 */
.rounded-lg {
  transition: all 0.3s ease;
}

.rounded-lg:hover {
  transform: scale(1.05);
}
</style>